import remoteSearchProductInput from '../remote-search-product-input';
import remoteSearchEmpInput from '../remote-search-emp-input';
import {
	spinSpecSheetAudit,
	spinSpecSheetClearAudit,
	spinSpecSheetClearSubmitAudit,
	spinSpecSheetCreate,
	spinSpecSheetGet,
	spinSpecSheetUpdate,
	spinSpecSheetUpdateAudit,
	spinSpecSheetUpdateAuditState
} from '../../../../../api/technology/order';
import { spinProcessPage } from '../../../../../api/technology/process';
import { spinMachineModelPage } from '../../../../../api/basicData/machineModel';
import handlerCache from '../../../../../mixins/handler-cache';
import remoteSearchBatchCodeInput
	from '../../../../production/qhPrd/productConfigCotton/components/remote-search-batch-code-input';
import { spinSpecSheetTaskGet } from '../../../../../api/production/xsNotice';
import { formatDate } from '../../../../../utils/jk/jk-tool';
import jkSaveButton from '../../../../jk-components/jk-save-button';
import jkUpdateButton from '../../../../jk-components/jk-update-button';
import { systemBusinessDictPage } from '../../../../../api/basicData/businessDict';
import batchSetPopover from '../batch-set-popover';
import { mathJsAdd, mathJsMul, mathJsSub } from '../../../../../utils/jk/jk-cals';
import { spinTechnologyModelPage } from '../../../../../api/technology/item';
import Log from '@/views/infra/job/log.vue';

let _this = null;
export default {
	components: {
		batchSetPopover,
		jkSaveButton, jkUpdateButton, remoteSearchProductInput, remoteSearchEmpInput, remoteSearchBatchCodeInput },
	mixins: [handlerCache],
	props: {
		pageType: {
			type: String,
			default: 'add'
		}
	},
	data() {
		const validateGm = (rules, value, callback) => {
			if (value && _this.ruleForm.gramWeight && _this.ruleForm.meters) {
				return callback();
			} else {
				return callback(new Error());
			}
		};
		return {
			prefix: 'spin:specSheet',
			spinTypeList: [],
			dataId: null,
			apiItem: {
				'save': spinSpecSheetCreate,
				'enable': spinSpecSheetUpdateAuditState,
				'update': spinSpecSheetUpdate,
				'updateAudit': spinSpecSheetUpdateAudit,
				'submit': spinSpecSheetUpdate, // 后端暂时没有'保存并提交接口'，先用update代替
				'cancelSubmit': spinSpecSheetClearSubmitAudit,
				'submitAudit': spinSpecSheetUpdateAudit,
				'audit': spinSpecSheetAudit,
				'cancelAudit': spinSpecSheetClearAudit
			},
			tableData: [],
			tableLoading: false,
			processList: [],
			updateAuditLoading: false,
			auditStateLoading: false,
			saveBtnLoading: false,
			saveAndEnableBtnLoading: false,
			workshopList: [],
			showLoading: true,
			saveDialogState: false,
			machineModelList: [],
			ruleForm: {
				'code': '',
				'spinTypeIdName': '',
				'batchCode': '',
				'dailyYield': null,
				'efficiencyPercent': null,
				'fixedLength': null,
				'gramWeight': null,
				'machineModelCode': '',
				'machineModelId': null,
				'machineModelName': '',
				'meters': null,
				'moistureRegain': null,
				'numbers': null,
				'processCode': '',
				'processId': null,
				'processName': '',
				'productCode': '',
				'productId': null,
				'productModels': '',
				'productName': '',
				'specDate': '',
				'specEmpId': null,
				'specEmpName': ''
			},
			rules: {
				gramWeight: [{ required: true, validator: validateGm, trigger: 'change' }],
				meters: [{ required: true, trigger: 'change' }],
				spinTypeId: [{ required: true, trigger: 'change' }],
				moistureRegain: [{ required: true, trigger: 'change' }],
				fixedLength: [{ required: true, trigger: 'change' }],
				efficiencyPercent: [{ required: true, trigger: 'change' }],
				dailyYield: [{ required: true, trigger: 'change' }],
				specEmpId: [{ required: true, trigger: 'change' }],
				productId: [{ required: true, trigger: 'change' }],
				machineModelId: [{ required: true, trigger: 'change' }],
				batchCode: [{ required: true, trigger: 'change' }],
				processId: [{ required: true, trigger: 'change' }],
				code: [{ required: true, trigger: 'change' }],
				name: [{ required: true, trigger: 'change' }]
			}
		};
	},
	methods: {
		handleKeyDown(event) {
			if (event.key === 'Enter') {
				event.preventDefault(); // 阻止默认行为

				// 获取当前聚焦的元素
				const currentElement = document.activeElement;

				// 获取所有可聚焦的元素
				const focusableElements = document.querySelectorAll('input');
				const currentIndex = Array.from(focusableElements).indexOf(currentElement);

				// 计算下一个应该聚焦的元素
				const nextIndex = (currentIndex + 1) % focusableElements.length;
				const nextElement = focusableElements[nextIndex];

				// 将焦点转移到下一个元素
				nextElement.focus();
			}
		},
		onCopyBtn() {
			this.$toOtherRouter({
				name: 'addTechnology',
				query: {
					isCopy: 1,
					id: this.ruleForm.id
				}
			});
		},
		onErrPerChange(e, scope) {
			if (e && this.tableData[scope.rowIndex].dataType === 1 && this.tableData[scope.rowIndex].plusOrMinus) {
				let val = mathJsMul(this.tableData[scope.rowIndex].val, (this.tableData[scope.rowIndex].plusOrMinus / 100));
				val = Number(val.toFixed(2));
				this.$set(this.tableData[scope.rowIndex], 'valMin', mathJsSub(this.tableData[scope.rowIndex].val, val));
				this.$set(this.tableData[scope.rowIndex], 'valMax', mathJsAdd(this.tableData[scope.rowIndex].val, val));
			} else {
				if (this.tableData[scope.rowIndex].dataType === 1) {
					this.$set(this.tableData[scope.rowIndex], 'valMin', this.tableData[scope.rowIndex].val);
					this.$set(this.tableData[scope.rowIndex], 'valMax', this.tableData[scope.rowIndex].val);
				}
			}
		},
		onConfirmBtnOfBatchPopover(e, keyName) {
			this.tableData.forEach(x => {
				this.$set(x, keyName, e);
			});
		},
		onSpinTypeChange() {
			this.tableData = [];
			this.getTechnologyItemListRequest();
		},
		onEditBtn() {
			this.$toOtherRouter({
				name: 'editTechnology',
				query: {
					id: this.$route.query.id ? Number(this.$route.query.id) : null
				}
			});
		},
		getSpinTypeListRequest() {
			return systemBusinessDictPage({ categoryCode: 'SPIN_TYPE' }).then(res => {
				if (res.data.status === 200) {
					this.spinTypeList = res.data.res || [];
				}
			});
		},
		async getDependentData() {
			this.showLoading = true;
			this.dataId = this.$route.query.id ? Number(this.$route.query.id) : null;
			this.$nextTick(() => {
				this.$refs.ruleForm.clearValidate();
			});
			await this.getSpinTypeListRequest();
			// 详情页不请求依赖的接口
			if (this.pageType !== 'detail') {
				await this.getMachineModelListRequest();
				await this.getProcessListRequest();
			}
			// 新增页
			if (this.pageType === 'add') {
				this.$set(this.ruleForm, 'specDate', formatDate(Date.now()));
				this.$set(this.ruleForm, 'specEmpId', this.$store.state.user.empInfo.id);
				this.$set(this.ruleForm, 'specEmpName', this.$store.state.user.empInfo.name);
				// 来源工艺任务时
				if (this.$route.query.technologyTaskId) {
					await this.getTechnologyTaskDetailRequest(this.$route.query.technologyTaskId).then(res => {
						if (res.data.status === 200) {
							const resData = res.data.res;
							this.$set(this.ruleForm, 'productId', resData.productId);
							this.$set(this.ruleForm, 'productCode', resData.productCode);
							this.$set(this.ruleForm, 'productName', resData.productName);
							this.$set(this.ruleForm, 'productModels', resData.productModels);
							this.$set(this.ruleForm, 'batchId', resData.batchId);
							this.$set(this.ruleForm, 'batchCode', resData.batchCode);
							const processItem = this.processList.find(x => x.code.toUpperCase() === (resData.prdNotice.processCode ? resData.prdNotice.processCode : 'XS').toUpperCase());
							this.$set(this.ruleForm, 'processId', processItem.id);
							this.$set(this.ruleForm, 'processCode', processItem.code);
							this.$set(this.ruleForm, 'processName', processItem.name);
						}
					});
				}
			}
			// 详情页不请求依赖的接口
			if (this.pageType !== 'detail') await this.getTechnologyItemListRequest();
			if (this.dataId) await this.getDetailRequest();
			this.showLoading = false;
		},
		setDependentDataOfForm() {
			const params = JSON.parse(JSON.stringify(this.ruleForm));
			params.processCode = this.processList.find(x => x.id === params.processId).code;
			params.processName = this.processList.find(x => x.id === params.processId).name;
			params.machineModelCode = this.machineModelList.find(x => x.id === params.machineModelId).code;
			params.machineModelName = this.machineModelList.find(x => x.id === params.machineModelId).name;
			params.specSheetParamList = JSON.parse(JSON.stringify(this.tableData));
			return params;
		},
		onProcessChange() {
			this.tableData = [];
			this.getTechnologyItemListRequest();
		},
		onSelectBatchCodeChange(e) {
			if (Object.keys(e).length) {
				this.$set(this.ruleForm, 'batchCode', e.batchCode);
			}
		},
		onSelectEmpChange(e) {
			if (Object.keys(e).length) {
				this.$set(this.ruleForm, 'specEmpId', e.id);
				this.$set(this.ruleForm, 'specEmpCode', e.code);
				this.$set(this.ruleForm, 'specEmpName', e.name);
			}
		},
		onSelectProductChange(e) {
			if (Object.keys(e).length) {
				this.setProductDependentData(e);
			}
		},
		setProductDependentData(e) {
			this.$set(this.ruleForm, 'batchCodeId', null);
			this.$set(this.ruleForm, 'batchCode', '');
			this.$set(this.ruleForm, 'productId', e.id);
			this.$set(this.ruleForm, 'productCode', e.code);
			this.$set(this.ruleForm, 'productName', e.name);
			this.$set(this.ruleForm, 'productModels', e.models);

			this.$set(this.ruleForm, 'spinTypeId', e.spinTypeId);
			this.$set(this.ruleForm, 'spinTypeCode', e.spinTypeCode);
			this.$set(this.ruleForm, 'spinTypeName', e.spinTypeName);

			this.$set(this.ruleForm, 'productSpinTypeId', e.spinTypeId);
			this.$set(this.ruleForm, 'productSpinTypeCode', e.spinTypeCode);
			this.$set(this.ruleForm, 'productSpinTypeName', e.spinTypeName);
			// 纺纱方式：如果品种上没有纺纱方式，则从品种名称模糊查"竹节"，付默认值
			/* if (!this.ruleForm.productSpinTypeId) {
				const names = '竹节';
				if (this.ruleForm.productName.indexOf(names) !== -1 && this.spinTypeList.find(x => x.name.indexOf(names) !== -1)) {
					const item = this.spinTypeList.find(x => x.name.indexOf(names) !== -1);
					this.$set(this.ruleForm, 'spinTypeId', item.id);
					this.$set(this.ruleForm, 'spinTypeCode', item.code);
					this.$set(this.ruleForm, 'spinTypeName', item.name);
				}
			}*/
		}, defaultRowData() {
			return {
				processId: null, processCode: '', processName: ''
			};
		}, getParamData(type) {
			const params = JSON.parse(JSON.stringify(this.ruleForm));
			if (type === 2) {
				params.auditState = 1;
			}
			const processItem = this.processList.find(x => x.id === params.processId) || {};
			params.processCode = processItem.code;
			params.processName = processItem.name;

			params.specSheetParamList = JSON.parse(JSON.stringify(this.tableData));

			const modelItem = this.machineModelList.find(x => x.id === params.machineModelId) || {};
			params.machineModelCode = modelItem.code;
			params.machineModelName = modelItem.name;

			const spinTypeItem = this.spinTypeList.find(x => x.id === params.spinTypeId) || {};
			params.spinTypeCode = spinTypeItem.code;
			params.spinTypeName = spinTypeItem.name;

			return params;
		}, onConfirmBtn(type) {
			this.$refs['ruleForm'].validate(valid => {
				if (valid) {
					this.saveRequest(type);
				} else {
					this.$tipsBar(this, 'validator');
				}
			});
		}, saveRequest(type) {
			if (type === 2) {
				this.saveAndEnableBtnLoading = true;
			} else {
				this.saveBtnLoading = true;
			}
			// 新增
			if (!this.dataId || this.$route.query.isCopy) {
				this.ruleForm.id = null;
				this.apiItem.save(this.getParamData(type)).then(res => {
					this.saveBtnLoading = false;
					this.saveAndEnableBtnLoading = false;
					if (res.data.status === 200) {
						this.dataId = res.data.res;
						this.$tipsBar(this, 'save');
						this.onJump(res.data.res);
					}
				});
				return;
			}
			// 编辑
			this.apiItem.update(this.getParamData(type)).then(res => {
				this.saveBtnLoading = false;
				this.saveAndEnableBtnLoading = false;
				if (res.data.status === 200) {
					this.$tipsBar(this, 'save');
					this.getDependentData();
				}
			});
		}, onAuditStateChange() {
			this.auditStateLoading = true;
			this.enableRequest(this.dataId).then(res => {
				this.auditStateLoading = false;
				if (res.data.status === 200) {
					this.getDependentData();
				}
			});
		}, enableRequest(id) {
			return spinSpecSheetUpdateAuditState({ id });
		}, onVisibleChange(e) {
			this.$emit('on-visible-change', e);
			if (!e) {
				Object.assign(this.$data, this.$options.data());
				this.$nextTick(() => {
					this.$refs.ruleForm.resetFields();
				});
			}
		}, getDetailRequest() {
			return spinSpecSheetGet({ id: this.dataId }).then(res => {
				this.showLoading = false;
				if (res.data.status === 200) {
					const resData = JSON.parse(JSON.stringify(res.data.res));
					delete resData.specSheetParamList;
					this.ruleForm = resData;
					this.tableData = res.data.res.specSheetParamList ? res.data.res.specSheetParamList.map(x => {
						x.val = x.dataType === 1 ? Number(x.val) : x.val;
						x.valMax = x.dataType === 1 ? Number(x.valMax) : x.valMax;
						x.valMin = x.dataType === 1 ? Number(x.valMin) : x.valMin;
						return x;
					}) : [];
					this.originalTableData = [...this.tableData];
					// 复制
					if (this.$route.query.isCopy) {
						delete this.ruleForm.id;
						this.tableData.forEach(x => {
							if (this.$route.query.isCopy) {
								delete x.id;
							}
						});
						this.$set(this.ruleForm, 'code', '');
						this.$set(this.ruleForm, 'businessCode', '');
						this.$set(this.ruleForm, 'specDate', formatDate(Date.now()));
						this.$set(this.ruleForm, 'specEmpId', this.$store.state.user.empInfo.id);
						this.$set(this.ruleForm, 'specEmpName', this.$store.state.user.empInfo.name);
					}
				}
			});
		}, getProcessListRequest() {
			return spinProcessPage({ auditState: 1 }).then(res => {
				if (res.data.status === 200) {
					this.processList = res.data.res || [];
				}
			});
		}, getMachineModelListRequest() {
			return spinMachineModelPage({ auditState: 1 }).then(res => {
				if (res.data.status === 200) {
					this.machineModelList = res.data.res || [];
				}
			});
		}, getTechnologyItemListRequest() {
			if (!this.ruleForm.processId) return;
			return spinTechnologyModelPage({
				auditState: 1,
				processId: this.ruleForm.processId,
				spinTypeId: this.ruleForm.spinTypeId,
				machineModelId: this.ruleForm.machineModelId
			}).then(res => {
				if (res.data.status === 200) {
					const resData = res.data.res || [];
					if (resData.length && resData[0].itemList) {
						// 遍历 resData[0].itemList 并查找匹配项
						resData[0].itemList = resData[0].itemList.map(data => {
							const match = this.originalTableData.find(item => item.technologyModelItemId === data.id);
							if (match) {
								// 如果匹配，将 originalTableData 中的匹配项赋值给 itemList 中的项
								return { ...data, ...match };
							}
							return {
								technologyModelItemId: data.id,
								dataType: data.dataType,
								ifBusi: data.ifBusi,
								ifNull: data.ifNull,
								ifWarning: data.ifWarning,
								specParamId: data.itemId,
								specParamCode: data.itemCode,
								specParamName: data.itemName,
								paramType: data.paramType,
								val: null,
								valMax: null,
								valMin: null
							}; // 保留原始项
						});
						this.tableData = resData[0].itemList;
					} else {
						this.tableData = [];
					}
				}
			});
		}, // 获取工艺任务的详情
		getTechnologyTaskDetailRequest(id) {
			return spinSpecSheetTaskGet({ id });
		}, onJump(id) {
			this.$store.dispatch('tagsView/delView', { path: this.$route.path });
			this.$toOtherRouter({
				name: 'editTechnology', query: { id }
			});
		}, onJumpList() {
			this.$store.dispatch('tagsView/delView', { path: this.$route.path });
			this.$toMainRouter({
				name: 'TechnologyOrder'
			});
		}, clearCacheMethod() {
			// Object.assign(this.$data, this.$options.data());
			this.$nextTick(() => {
				this.$refs.ruleForm.clearValidate();
				this.getDependentData();
			});
		}
	}, mounted() {
		_this = this;
	}
};
